/*Purpose: Merge permid variable onto tradeline, public record, inquiry, collections, and summary files.  We merge from the header file and use teditseq.  */
  /*We do this because teditseq  is "messed up" (un-mergeable) on the rollup file, so in order to merge tradelines with rollup, we must use permid.*/

libname save "data" ;   

/*header records*/
data head;
     set save.header2007_june(keep=teditseq permid2004);
run;

proc sort data=head;
     by teditseq;
run;

/*trade records*/
proc sort data=save.trade2007_june;
     by teditseq;
run;

/* merge by teditseq to get permid variable on trade file*/
/* number of unique teditseq on trade file before = number of unique teditseq and permid after merge, that means everyone has a permid, and it's a good merge*/
data save.trade2007_june(rename=(permid2004=permid));
     merge head(in=in1) save.trade2007_june(in=in2);
     by teditseq;
     if in1 and in2;
run;
/*
proc sql;
select count(distinct teditseq) as UniqueTESQ,
       count(distinct permid) as Uniquepermid,
       count(*) as nobs
       from save.trade2007_june;
quit;
run;
endsas;
*/


/*inquiry records*/
proc sort data=save.inquiry2007_june;
     by teditseq;
run;

/* merge by teditseq to get permid variable on inquiry file*/
data save.inquiry2007_june(rename=(permid2004=permid));
     merge head(in=in1) save.inquiry2007_june(in=in2);
     by teditseq;
     if in1 and in2;
run;

/*public records records*/
proc sort data= save.pubrec2007_june;
     by teditseq;
run;

/* merge by teditseq to get permid variable on pubrec file*/
data save.pubrec2007_june(rename=(permid2004=permid));
     merge head(in=in1) save.pubrec2007_june(in=in2);
     by teditseq;
     if in1 and in2;
run;

/*collections records*/
proc sort data= save.collect2007_june;
     by teditseq;
run;

/* merge by teditseq to get permid variable on collections file*/
data save.collect2007_june(rename=(permid2004=permid));
     merge head(in=in1) save.collect2007_june(in=in2);
     by teditseq;
     if in1 and in2;
run;

/*summary records*/
proc sort data= save.summary2007_june;
     by teditseq;
run;

/* merge by teditseq to get permid variable on summary file*/
data save.summary2007_june(rename=(permid2004=permid));
     merge head(in=in1) save.summary2007_june(in=in2);
     by teditseq;
     if in1 and in2;
run;

proc contents data=save.summary2007_june;
run;
